package com.tool.utils;

import java.io.*;

public class writeToFileUtils {

    /**
     * 将模板内容写入目标文件
     *
     * @param templatePath 模板文件路径
     * @param targetFile   目标文件
     * @param packageName  包名
     */
    public static void writeToFile(String templatePath, File targetFile, String packageName) throws IOException {
        try (
                InputStream in = new FileInputStream(templatePath);
                InputStreamReader inr = new InputStreamReader(in, "utf-8");
                BufferedReader br = new BufferedReader(inr);
                OutputStream out = new FileOutputStream(targetFile);
                OutputStreamWriter outw = new OutputStreamWriter(out, "utf-8");
                BufferedWriter bw = new BufferedWriter(outw)
        ) {
            // 写入包名
            bw.write("package " + packageName + ";");
            bw.newLine();
            bw.newLine();

            // 写入模板内容
            String line;
            while ((line = br.readLine()) != null) {
                bw.write(line);
                bw.newLine();
            }
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace(); // 处理异常
        }
    }
}
